package april.fastjson.type_reference;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

public class TypeReferenceDemo {

	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {

		List<Map> maplist = new ArrayList<Map>();
		List<List> list = new ArrayList<List>();

		Map<String, Bean> beanMap = new HashMap<String, Bean>();

		beanMap.put("a", new Bean(0, "hello"));
		beanMap.put("b", new Bean(1, "world"));
		beanMap.put("c", new Bean(2, "happy"));

		maplist.add(beanMap);
		list.add(maplist);

		String text = JSON.toJSONString(list);
		System.out.println(text);

		// TypeReference 类型索引
		List<List<Map<String, Bean>>> list2 = JSON.parseObject(text,
				new TypeReference<List<List<Map<String, Bean>>>>() {
				});

		/**
		 * 这种方式是 错误的
		 * 
		 * Exception in thread "main" java.lang.ClassCastException:
		 * com.alibaba.fastjson.JSONObject cannot be cast to
		 * april.fastjson.type_reference.TypeReferenceDemo$Bean at
		 * april.fastjson
		 * .type_reference.TypeReferenceDemo.main(TypeReferenceDemo.java:38)
		 */
		// List<List<Map<String, Bean>>> list2 = JSON.parseObject(text,
		// List.class);

		Map<String, Bean> map = list2.get(0).get(0);

		System.out.println(map.get("a").getId() + " " + map.get("a").getName());
	}

	public static class Bean {
		private int id;
		private String name;

		public Bean() {

		}

		public Bean(int id, String name) {
			this.id = id;
			this.name = name;
		}

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

}
